package org.android.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.iati.mobile.Filter;
import org.iati.mobile.IATI;
import org.iati.mobile.IATIImpl;
import org.iati.mobile.exception.IATIBadFilterException;
import org.iati.mobile.exception.IATIException;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class IATIDemoResults extends ListActivity implements OnScrollListener {
	private String donorID;
	private String sectorID;
	private String countryID;
	private String organizationID;

	private Map<String, String> projectsByDonor;
	private TextView numberOfProjects;

	private IATI mIATI;

	private String selectedProject;

	private ProgressDialog progressDialog;
	private ProjectAdapter mProjectAdapter;

	private Filter filter;

	private String serverURL;
	private String serverPort;
	SharedPreferences pref;

	private final static String TAG = "debug";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.iatidemoresults);

		mProjectAdapter = new ProjectAdapter (this);
		setListAdapter (mProjectAdapter);

		pref = PreferenceManager.getDefaultSharedPreferences(this);
		serverURL = pref.getString("url", "http://iati-collector.devgw.org");
		serverPort = pref.getString("port", "80");

		mIATI = new IATIImpl(serverURL, serverPort);

		numberOfProjects = (TextView) findViewById(R.id.numberOfProjects);

		// Get the intent, and save the IDs
		Intent intent = getIntent();
		donorID = intent.getStringExtra("donorID");
		sectorID = intent.getStringExtra("sectorID");
		countryID = intent.getStringExtra("countryID");
		organizationID = intent.getStringExtra("organizationID");

		filter	= new Filter();
		if ( donorID != null && !donorID.equals("-1") )
			filter.addDonorId(donorID);
		if ( sectorID != null && !sectorID.equals("-1") )
			filter.addSectorId(sectorID);
		if ( countryID != null && !countryID.equals("-1") )
			filter.addCountryId(countryID);
		if ( organizationID != null && !organizationID.equals("-1") )
			filter.addReportingOrgId(organizationID);

		Log.v (TAG, "donorID: " + donorID);
		Log.v (TAG, "sectorID: " + sectorID);
		Log.v (TAG, "countryID: " + countryID);
		Log.v (TAG, "organizationID: " + organizationID);

		try {
			Log.v ("FILTER", "Filter: " + filter.generate() );
		} catch (IATIBadFilterException e1) {
			e1.printStackTrace();
		}

		getListView().setOnItemClickListener (new OnItemClickListener() {
			public void onItemClick(AdapterView<?> listAdapter, View view, int position, long id) {
				ProjectList mProjectList = (ProjectList)mProjectAdapter.getItem (position);
				String selectedItem = mProjectList.getProjectTitle();

				selectedProject = "";

				for (Entry<String, String> entry : projectsByDonor.entrySet()) {
					if (entry.getKey() != null && selectedItem.equals(entry.getValue())) {
						selectedProject = entry.getKey();
					}
				}

				Log.d(TAG, "selectedProject: " + selectedProject);

				Intent intent = new Intent (IATIDemoResults.this, IATIDemoProject.class);
				intent.putExtra("iatiID", selectedProject);
				IATIDemoResults.this.startActivity(intent);
			}
		});

		getListView().setOnScrollListener(this);

		final Runnable runnable = new Runnable() {
			public void run() {
				try {
					//projectsByDonor = mIATI.getProjectsByDonor(donorID);
					projectsByDonor = mIATI.getProjectsByFilter(filter);

					// remove the empty entries
					Iterator<Entry<String, String>> entries = projectsByDonor.entrySet().iterator();
					while (entries.hasNext()) {
						Entry<String, String> mEntry = entries.next();
						if (mEntry.getKey() == null ||  mEntry.getValue() == null) {
							entries.remove();
						}
					}

					// update the UI
					runOnUiThread(new Runnable() {
						public void run() {
							ArrayList<String> projects = new ArrayList<String>(projectsByDonor.values());
							for (String project : projects)
								mProjectAdapter.addActivity(project);

							numberOfProjects.setText("" + mProjectAdapter.getCount());
						}
					});

					// dismiss the progress dialog
					if(progressDialog != null) 
						progressDialog.dismiss();
				} catch (IOException e) {
					if(progressDialog != null) 
						progressDialog.dismiss();
					e.printStackTrace();
				} catch (IATIException e) {
					if(progressDialog != null) 
						progressDialog.dismiss();
					e.printStackTrace();
				}
			}
		};

		// show the progress dialog
		progressDialog = ProgressDialog.show(IATIDemoResults.this, "", "Loading...", true, true);

		// run on background thread.
		performOnBackgroundThread(runnable);
	}

	/**
	 * Executes the network requests on a separate thread.
	 * 
	 * @param runnable The runnable instance containing network operations to be executed.
	 */
	public static Thread performOnBackgroundThread(final Runnable runnable) {
		final Thread mThread = new Thread() {
			@Override
			public void run() {
				try {
					runnable.run();
				} finally {
					// ...
				}
			}
		};
		mThread.start();
		return mThread;
	}

	public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {

		/* maybe add a padding */
		boolean loadMore = firstVisible + visibleCount >= totalCount;
		Log.d (TAG, "firstVisible: " + firstVisible + "  visibleCount: " + visibleCount + "  totalCount: " + totalCount + "  loadMore: " + loadMore);

		if(loadMore) {
			//adapter.count += visibleCount; // or any other amount
			//adapter.notifyDataSetChanged();
			//adapter.add("aaaa");
		}
	}

	public void onScrollStateChanged(AbsListView v, int s) { 

	}    
}
